#!/usr/bin/python
# -*- coding:utf-8 -*-

import re
from django.contrib.auth.models import AnonymousUser
from mongoengine.errors import DoesNotExist
from .account_utils import Singleton
from .models import UserGroups


class CachePermission(Singleton):
    def __init__(self):
        self.permission = dict()

    def _update_permission(self, group):
        try:
            user_group = UserGroups.objects.get(group=group)
            self.permission[group] = [
                re.compile(f"{p.path}=={p.method}") for p in user_group.permissions
            ]
        except DoesNotExist:
            return

    def _get_permission(self, group):
        if not self.permission.get(group):
            self._update_permission(group)
        return self.permission.get(group, [])

    def get_permission(self, groups):
        if isinstance(groups, str):
            return self._get_permission(groups)
        if isinstance(groups, list):
            permissions = set()
            for group in groups:
                permissions.update(set(self._get_permission(group)))
            return list(permissions)
        return []

    def update_permission(self, groups):
        if isinstance(groups, str):
            self._update_permission(groups)
        if isinstance(groups, list):
            for group in groups:
                self._update_permission(group)


cache_permission = CachePermission()


def check_permission(request):
    permission = f"{request.path_info}=={request.method}"
    if isinstance(request.user, AnonymousUser):
        return
    if request.user.is_superuser:
        return True
    user_group = request.user.group or []
    groups = [g.group for g in user_group]
    permissions = cache_permission.get_permission(groups)
    return any([p.fullmatch(permission) for p in permissions])


def check_api_permission(request):
    permission = f"{request.path_info}=={request.method}"
    permissions = cache_permission.get_permission(["api"])
    return any([p.fullmatch(permission) for p in permissions])
